package com.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.erp.Util.WebUtil;
import com.erp.comm.ResultCode;
import com.erp.pojo.LoginInfo;
import com.erp.pojo.UserInfo;
import com.erp.service.LoginInfoService;
import com.erp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;


@RestController
@RequestMapping("login")
public class LoginController {


    @Autowired
    private LoginInfoService loginInfoService;

    @Autowired
    private UserService userService;


    @RequestMapping("login")
    public ResultCode login(String loginname, String pwd){

        //添加一条登录信息
        LoginInfo logininfo = new LoginInfo();
        logininfo.setLoginname(loginname);

        //获取请求ip地址
        logininfo.setLoginip(WebUtil.getRequest().getRemoteAddr());
        logininfo.setLogintime(new Date());
        loginInfoService.save(logininfo);


        //loginname和pwd进行查询
        QueryWrapper<UserInfo> qw = new QueryWrapper<>();
        qw.eq("loginname", loginname).eq("pwd", pwd);
        UserInfo user = userService.getOne(qw);

        if(user != null){
            WebUtil.getSession().setAttribute("user",user);


            return ResultCode.SUCCESS_LOGIN;
        } else {
            return ResultCode.FAIL_LOGIN;
        }
    }

}
